/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * frmLogin.java
 *
 * Created on 23-02-2011, 21:10:19
 */
package GUI;

import entity.RememberLogin;
import interact.ValidateData;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;
import javax.swing.JDesktopPane;
import org.netbeans.lib.awtextra.AbsoluteConstraints;

/**
 *
 * @author UnderGround
 */
public class frmLogin extends javax.swing.JFrame {

    private String username, password;
    private MainFrame home;
    Image image;
    private Config config = new Config();
    private boolean flag = false;
    private JDesktopPane deskPan = new JDesktopPane();
    private ObjectOutputStream fos = null;

    /** Creates new form frmLogin */
    public frmLogin() {
        Image icon = getToolkit().getImage(getClass().getResource("/images/soft_icon.png"));
        setIconImage(icon);
//        interact.connect.configServer();
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
        }
//        setUndecorated(true);
        initComponents();
        this.setVisible(true);
        LoadRemember();


    }

    public void LoadRemember() {
        File file = new File("remember.dat");
        if (file.exists()) {
            ObjectInputStream fis = null;
            try {

                fis = new ObjectInputStream(new FileInputStream("remember.dat"));
                entity.RememberLogin re = (RememberLogin) fis.readObject();
                String pass = interact.MD5.getHashString(String.valueOf(re.getPassword()).trim());
                String sql = "select * from tblAdministrator where UserName  = '" + re.getUsername() + "' and Password = '" + pass + "'";
                txtUsername.setText(re.getUsername());
                txtPassword.setText(re.getPassword());
                chekRemember.setSelected(re.isCheck());
            } catch (IOException ex) {
                Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                try {
                    fis.close();
                } catch (IOException ex) {
                    Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jDesktopPane1 = new javax.swing.JDesktopPane();
        iconte = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtUsername = new javax.swing.JTextField();
        txtPassword = new javax.swing.JPasswordField();
        btnLogin = new javax.swing.JButton();
        chekRemember = new javax.swing.JCheckBox();
        btnExit = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        txtConfig = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(255, 255, 255));
        setMinimumSize(new java.awt.Dimension(350, 280));
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        iconte.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/login.png"))); // NOI18N
        getContentPane().add(iconte, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 350, 60));

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel2.setText("User name");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 80, 73, -1));

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel3.setText("Password");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 120, 73, -1));

        txtUsername.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtUsernameKeyTyped(evt);
            }
        });
        getContentPane().add(txtUsername, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 80, 156, -1));

        txtPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtPasswordKeyTyped(evt);
            }
        });
        getContentPane().add(txtPassword, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 120, 156, -1));

        image = Toolkit.getDefaultToolkit().getImage(getClass().getResource("/Images/ok.png"));
        btnLogin.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/login_1.png"))); // NOI18N
        btnLogin.setText("Login");
        btnLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoginActionPerformed(evt);
            }
        });
        getContentPane().add(btnLogin, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 180, 90, -1));

        chekRemember.setText("Remember password");
        getContentPane().add(chekRemember, new org.netbeans.lib.awtextra.AbsoluteConstraints(140, 140, -1, -1));

        btnExit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/exit_1.png"))); // NOI18N
        btnExit.setText("Exit");
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });
        getContentPane().add(btnExit, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 180, -1, -1));

        jPanel1.setBackground(new java.awt.Color(255, 255, 204));
        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jPanel1.setForeground(new java.awt.Color(255, 255, 255));

        txtConfig.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/config.png"))); // NOI18N
        txtConfig.setText("Config");
        txtConfig.setMaximumSize(new java.awt.Dimension(50, 16));
        txtConfig.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                txtConfigMouseClicked(evt);
            }
        });
        jPanel1.add(txtConfig);

        getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 200, 70, 30));

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-366)/2, (screenSize.height-277)/2, 366, 277);
    }// </editor-fold>//GEN-END:initComponents

    public void login() {

        Vector userInfo;
        String pass = new String(txtPassword.getPassword());
        username = txtUsername.getText().trim();
        password = interact.MD5.getHashString(String.valueOf(txtPassword.getPassword())).trim();
        System.out.println("u" + username);
        System.out.println("p" + password);

        txtUsername.setBackground(java.awt.Color.white);
        txtPassword.setBackground(java.awt.Color.white);
        if (!ValidateData.checkEmpty(username, txtUsername)) {
            ValidateData.showMessage("Username can't is empty");
            txtUsername.setBackground(new java.awt.Color(250, 255, 168));
            txtUsername.requestFocus();
            return;
        }
        if (password.equals("d41d8cd98f00b204e9800998ecf8427e")) {
            ValidateData.showMessage("Password can't is empty");
            return;
        }

        String sql = "select * from tblAdministrator where Username = '" + username + "' and Password = '" + password + "'";
        userInfo = interact.LoginInteraction.getUserInfo(sql);
        boolean status = false;

        if (userInfo.size() > 0) {
            for (int i = 0; i < userInfo.size(); i++) {

                Vector temp = (Vector) userInfo.elementAt(i);
                System.out.println(temp.elementAt(2));
                System.out.println(temp.elementAt(1));


                if (username.toString().equals(temp.elementAt(1).toString().trim()) && password.toString().equals(temp.elementAt(2).toString().trim())) {
                    status = true;
                    System.out.println("dang nhap ok");
                    if (chekRemember.isSelected() == true) {
                        try {
                            fos = new ObjectOutputStream(new FileOutputStream("remember.dat"));
                            entity.RememberLogin remember = new RememberLogin(username, pass, true);
                            fos.writeObject(remember);

                        } catch (IOException ex) {
                            System.out.println("not found the file");
                            Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    } else {
                        try {
                            fos = new ObjectOutputStream(new FileOutputStream("remember.dat"));
                            entity.RememberLogin remember = new RememberLogin("", "", false);
                            fos.writeObject(remember);
                        } catch (IOException ex) {
                            Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
                        } finally {
                            try {
                                fos.close();
                            } catch (IOException ex) {
                                Logger.getLogger(frmLogin.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                    Home.userLogin = username;
                    dispose();
                    Home home = new Home();
                    home.setVisible(true);
                }
            }
        } else {
            ValidateData.showMessage("wrong username or password");
        }
    }
    private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoginActionPerformed
        login();
    }//GEN-LAST:event_btnLoginActionPerformed

    private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
        System.exit(0);
    }//GEN-LAST:event_btnExitActionPerformed

    private void txtUsernameKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUsernameKeyTyped
        if (evt.getKeyChar() == KeyEvent.VK_ENTER) {
            login();
        }
    }//GEN-LAST:event_txtUsernameKeyTyped

    private void txtPasswordKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPasswordKeyTyped
        if (evt.getKeyChar() == KeyEvent.VK_ENTER) {
            login();
        }
    }//GEN-LAST:event_txtPasswordKeyTyped

    private void txtConfigMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtConfigMouseClicked
        if (!flag) {
            flag = !flag;
            txtConfig.setText("Hide");
            this.setSize(350, 470);
            config.setVisible(false);
            this.add(config, new AbsoluteConstraints(0, 230, 350, 200));
            config.setVisible(true);
            pack();
        } else {
            flag = !flag;
            txtConfig.setText("Config");
            this.remove(config);
            this.setSize(350, 280);
            pack();
        }
    }//GEN-LAST:event_txtConfigMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new frmLogin().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnExit;
    private javax.swing.JButton btnLogin;
    private javax.swing.JCheckBox chekRemember;
    private javax.swing.JLabel iconte;
    private javax.swing.JDesktopPane jDesktopPane1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel txtConfig;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JTextField txtUsername;
    // End of variables declaration//GEN-END:variables
}
